package 可重入锁.lock的不同方式.中断响应;

import java.util.concurrent.locks.ReentrantLock;

public class lockInterruptibly extends Thread {
    private static ReentrantLock lock1 = new ReentrantLock();// 静态的!
    private static ReentrantLock lock2 = new ReentrantLock();// 静态的!
    private int i;

    public lockInterruptibly(int i) {
        this.i = i;
    }

    @Override
    public void run() {
        try {
            if (i == 1) {
                lock1.lockInterruptibly();// l1等待锁中，会响应中断
                Thread.sleep(500);
                lock2.lockInterruptibly();
            } else {
                lock2.lockInterruptibly();
                Thread.sleep(500);
                lock1.lockInterruptibly();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (lock1.isHeldByCurrentThread())
                lock1.unlock();
            if (lock2.isHeldByCurrentThread())
                lock2.unlock();
            System.out.println(Thread.currentThread().getName() + "退出");
        }
    }
    /*
        细节：
            虽然两个线程执行的是类不同对象，
                但是这两个线程用的都是该类的 “可重入锁”。
     */
    public static void main(String[] args) throws InterruptedException {
        lockInterruptibly l1 = new lockInterruptibly(1);
        lockInterruptibly l2 = new lockInterruptibly(2);
        l1.start();
        l2.start();
        Thread.sleep(1000);
        l1.interrupt();// 写上不会死锁，不写会死锁
    }
}
